import React from "react";
import PropTypes from "prop-types";

// components
import Profile from "./profile";

//utils
import {
  confirm,
  create,
  openSingleChat,
  alert as NativeAlert,
  toast,
  openLink
} from "../../utils/dingtalk.js";
import fetch from "../../utils/fetch.js";

// actions
import { fetchList } from "../../actions/todoList/";

import { deleteEmployee, regular, doctor } from "../../actions/growth/";

function getBtnText(
  scheduleType,
  scheduleStatus,
  userId,
  name,
  corpId,
  deptManagers = [],
  currentUserId,
  enableRegular,
  regularUrl
) {
  const BUTTONS = ["预约会议", "联系主管", "提醒员工发起转正"];

  if (scheduleType === "转正") {
    if (scheduleStatus === "2") {
      return <div className="todo-item-status">已转正</div>;
    } else if (scheduleStatus === "1") {
      return <div className="todo-item-status">已安排</div>;
    } else if (scheduleStatus === "0") {
      return (
        <div
          className="todo-item-btn"
          onClick={() =>
            dd.device.notification.actionSheet({
              title: "安排转正",
              cancelButton: "取消", //取消按钮文本
              otherButtons: BUTTONS,
              onSuccess: ({ buttonIndex }) => {
                window._rlog(`_todoList_action_${buttonIndex}`);
                if (buttonIndex === 0) {
                  // 预约会议
                  create({
                    users: deptManagers.concat(userId).concat(currentUserId),
                    corpId,
                    text: `【转正面谈】请准时参加${name}的转正面谈`,
                    cb: () => {
                      fetch(
                        "/hrmregister/mobile/hrmSchedule/updateRegularScheduleStatus",
                        {
                          body: {
                            userId
                          }
                        }
                      ).then(() => {
                        // 局部刷新，显示已安排 tag
                        fetchList()(window.store.dispatch);
                      });
                    }
                  });
                } else if (buttonIndex === 1) {
                  // 联系主管和员工

                  // 没有主管
                  if (!deptManagers || deptManagers.length === 0) {
                    NativeAlert({
                      message: "当前员工无主管",
                      buttonName: "我知道了"
                    });
                  } else {
                    openSingleChat({
                      corpId,
                      userId: deptManagers ? deptManagers[0] : ""
                    });
                  }
                } else if (buttonIndex === 2) {
                  // 提醒员工发起转正
                  if (!enableRegular) {
                    return NativeAlert({
                      message: "转正审批未开通，不能发送消息",
                      buttonName: "立即开通",
                      onSuccess() {
                        openLink(regularUrl);
                      }
                    });
                  }

                  doctor({ userId, type: "regular" })().then(res => {
                    if (res.success && res.result) {
                      return regular({ userId })().then(res => {
                        if (res.success) {
                          // 局部刷新
                          fetchList()(window.store.dispatch);
                          toast({ text: "已发送" });
                        }
                      });
                    } else {
                      NativeAlert({ message: "员工已发起离职交接。请在成长记录中查询" });
                    }
                  });
                }
              }
            })}
        >
          <button className="todo-extra-btn">安排转正</button>
        </div>
      );
    }
  }
  if (scheduleType === "离职") {
    if (scheduleStatus === "1") {
      return <div />;
    } else if (scheduleStatus === "2") {
      return <div className="todo-item-status">已离职</div>;
    } else if (scheduleStatus === "0") {
      return (
        <div
          className="todo-item-btn"
          onClick={() => {
            window._rlog(`_todoList_btn_leave`);
            confirm({
              message: "确认离职后，会将员工从通讯录删除，员工档案将永久保存",
              buttonLabels: ["取消", "确认"],
              cb: res => {
                window._rlog(`_todoList_btn_leave_${res.buttonIndex}`);
                if (res.buttonIndex === 1) {
                  deleteEmployee({ userId })().then(res => {
                    if (res.success) {
                      toast({
                        text: "已离职",
                        onSuccess() {
                          fetchList()(window.store.dispatch);
                        }
                      });
                    }
                  });
                }
              }
            });
          }}
        >
          <button className="todo-extra-btn">确认离职</button>
        </div>
      );
    }
  }
  if (scheduleType === "调岗") {
    if (scheduleStatus === "1") {
      return <div />;
    } else if (scheduleStatus === "2") {
      return <div />;
    } else if (scheduleStatus === "0") {
      return <div />;
    }
  }

  if (scheduleType === "入职") {
    if (scheduleStatus === "1") {
      return <div />;
    } else if (scheduleStatus === "2") {
      return <div className="todo-item-status">已入职</div>;
    } else if (scheduleStatus === "0") {
      return (
        <div
          className="todo-item-btn"
          onClick={() => {
            // fix bug: #13019971
            window.needReload = function() {
              if (
                window.location.href.toLocaleLowerCase().indexOf("todolist") !==
                -1
              ) {
                fetchList()(window.store.dispatch);
              }
            };
            openLink(`?userId=${userId}#confirm`);
          }}
        >
          <button className="todo-extra-btn">确认入职</button>
        </div>
      );
    }
  }
}

const TodoItem = ({
  scheduleType,
  userName,
  avatar,
  deptName,
  transAfterDeptName, // 上一部门
  scheduleStatus,
  day,
  isLast,
  delayDay,
  date,
  userId,
  deptManagers,
  isFirst,
  corpId,
  currentUserId,
  hrmScheduleContent,
  enableRegular,
  regularUrl
}) => (
  <div className={`todo-item${isLast ? "-last" : ""}`}>
    <Profile
      name={userName}
      avatar={avatar}
      dept={deptName}
      transAfterDeptName={transAfterDeptName}
      day={isFirst ? day : ""}
      delay={delayDay}
      date={date}
      userId={userId}
      hrmScheduleContent={hrmScheduleContent}
    />
    {getBtnText(
      scheduleType,
      scheduleStatus,
      userId,
      userName,
      corpId,
      deptManagers,
      currentUserId,
      enableRegular,
      regularUrl
    )}
  </div>
);

TodoItem.propTypes = {
  scheduleType: PropTypes.string,
  userName: PropTypes.string,
  avatar: PropTypes.string,
  deptName: PropTypes.string,
  scheduleStatus: PropTypes.string,
  day: PropTypes.string,
  isLast: PropTypes.string,
  delayDay: PropTypes.string,
  date: PropTypes.string,
  userId: PropTypes.string,
  isFirst: PropTypes.string,
  deptManagers: PropTypes.array,
  corpId: PropTypes.string,
  currentUserId: PropTypes.string,
  transAfterDeptName: PropTypes.string,
  hrmScheduleContent: PropTypes.object
};
export default TodoItem;
